package com.ruoyi.teaching.service.impl;

import com.alibaba.dashscope.app.Application;
import com.alibaba.dashscope.app.ApplicationParam;
import com.alibaba.dashscope.app.ApplicationResult;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.teaching.bo.CheckAnswerResultBo;
import com.ruoyi.teaching.service.LargeModelService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;


/**
 * 〈〉
 *
 * @author coach tam
 * @email 327395128@qq.com
 * @create 2023/12/23
 * @since 1.0.0
 * 〈坚持灵活 灵活坚持〉
 */
@Component
@Slf4j
public class BaiLianLargeModel implements LargeModelService {

    public static final String APP_ID = "asst_53e97105-95e9-4668-8a64-037677033fe8";
    public static final String API_KEY = "sk-HEm8zrNT7o";

    private final Application application = new Application();

    @Override
    public CheckAnswerResultBo checkAnswer(String question, String answer) throws Exception {
        CheckAnswerResultBo resultBo = new CheckAnswerResultBo();
        try {
            String prompt = "请评估以下面试题的回答情况，给出0至10分的评分，0为非常差，10为满分，并给出其他优秀建议。将评价、评分和建议按照标准json格式{\"评价\": \"xx\", \"评分\": 0, \"建议\": \"xx\"}返回。问题是:"+question+"  答案是:"+answer;
            ApplicationParam param = ApplicationParam.builder()
                    .appId(APP_ID)
                    .apiKey(API_KEY)
                    .prompt(prompt)
                    .topP(0.2)
                    .build();
            ApplicationResult result = application.call(param);
            log.info("requestId: {}, text: {}, finishReason: {}",
                    result.getRequestId(), result.getOutput().getText(), result.getOutput().getFinishReason());
            // 解析结果 json格式 {"评价": "xx", "评分": 0, "建议": "xx"} ,并消除多余的换行符和空格
            String text = result.getOutput().getText()
                    .replaceAll("\\n+", "")
                    .replaceAll("\\s+", "");
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(text);
            JsonNode node = jsonNode.get("评价");
            if (ObjectUtils.isNotEmpty(node)) {
                resultBo.setAppraise(node.asText());
            }
            node = jsonNode.get("评分");
            if (ObjectUtils.isNotEmpty(node)) {
                resultBo.setScore(node.asInt());
            }
            node = jsonNode.get("建议");
            if (ObjectUtils.isNotEmpty(node)) {
                resultBo.setAdvance(node.asText());
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return resultBo;
    }
}
